import 'package:alipay_kit/alipay_kit.dart';
import 'dart:async';

class AlipaySdkUtils {
  static AlipaySdkUtils? _instance;

  static AlipaySdkUtils getInstance() {
    if (_instance == null) {
      _instance = new AlipaySdkUtils._();
    }
    return _instance!;
  }

  bool _listenerPay = false;
  Function(AlipayResp resp)? _callback;
  bool _listenerLogin = false;

  AlipaySdkUtils._();

  /// 发起支付宝支付
  Future<AlipayResp> aliPay(String order, [bool isShowLoading = true]) {
    if (!_listenerPay) {
      _listenerPay = true;
      Alipay.instance.payResp().listen((resp) {
        if (_callback != null) {
          _callback!(resp);
        }
      });
    }
    Completer<AlipayResp> complete = Completer<AlipayResp>();
    _callback = (AlipayResp resp) {
      complete.complete(resp);
    };
    Alipay.instance
        .payOrderSign(orderInfo: order, isShowLoading: isShowLoading);

    return complete.future;
  }

  Future<AlipayResp> login(String info, [bool isShowLoading = true]) {
    if (!_listenerLogin) {
      _listenerLogin = true;
      Alipay.instance.authResp().listen((resp) {
        if (_callback != null) {
          _callback!(resp);
        }
      });
    }
    Completer<AlipayResp> complete = Completer<AlipayResp>();
    Alipay.instance.authSign(info: info, isShowLoading: isShowLoading);
    return complete.future;
  }

  /// 判断是否登录
  Future<bool> isInstalled() {
    return Alipay.instance.isInstalled();
  }
}
